package com.llpy.Service;

import com.llpy.dto.SlideDto;
import com.llpy.mapper.SlideMapper;
import com.llpy.pojo.Slide;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ApiSlideService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SlideMapper slideMapper;
    public List<Slide> findAllSlide(){
        Object object = redisTemplate.opsForValue().get("slide_");
        if(object !=null){
            return (List<Slide>) object;
        }else{
            //缓存没有，进入数据库查询
            List<Slide> slides = slideMapper.findAll();
            if(slides.size()>0){
                redisTemplate.opsForValue().set("slide_",slides,1, TimeUnit.HOURS);
                System.out.println("查询幻灯片~~~");
                return slides;
            }else{
                return null;
            }
        }
    }
    public List<Slide> updateSlide(List<SlideDto> slides){
        slideMapper.deleteAll();
        //遍历集合，存入新的幻灯片
        for (SlideDto slideDto : slides) {
            Slide slide = new Slide();
            slide.setUserImg(slideDto.getUserImg());
            slideMapper.save(slide);
        }
        List<Slide> slides1 = slideMapper.findAll();
        redisTemplate.opsForValue().set("slide_",slides1);
        return slides1;
    }
}
